package cn.yuanqiao.web.controller.archive.Identify;
/**
 * @author 赵常飞
 * @date 2023/7/10 10:15
 */

import cn.yuanqiao.archive.Identify.domain.TenantYqJdFile;
import cn.yuanqiao.archive.Identify.domain.TenantYqbgqxjdJob;
import cn.yuanqiao.archive.Identify.service.DisposeNewService;
import cn.yuanqiao.archive.Identify.service.IBgqxIdentifyService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.web.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 *@AUTHOR:赵常飞
 *@date 2023/7/10 10:15
 */
@RestController
@RequestMapping("/archive/bgqxidentify")
public class BgqxIdentifyController extends BaseController {
    @Autowired
    private IBgqxIdentifyService bgqxIdentifyService;

    @Autowired
    private DisposeNewService disposeNewService;
    /**
     * 获取数据列表
     */
    @Log(title = "保管期限鉴定获取档案列表", businessType = BusinessType.SELECT)
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = disposeNewService.getlist(json);
        return getDataTable(list);
    }
    /** 获取任务列表*/
    @Log(title = "保管期限鉴定获取任务列表", businessType = BusinessType.SELECT)
    @PostMapping("/bgqxjdjoblist")
    public TableDataInfo bgqxjdjoblist(@RequestBody JSONObject json)
    {
        startPage();
        List<Map<String,Object>> list = disposeNewService.bgqxjdjoblist(json);
        return getDataTable(list);
    }

    /** 添加任务 */
    @Log(title = "添加保管期限鉴定任务", businessType = BusinessType.INSERT)
    @PostMapping("/addjob")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:add')")
    public AjaxResult addjob(@RequestParam(value="remark",required=false)String remark, @RequestParam("jiandingrenwuname")String jiandingrenwuname, @RequestParam("renwuno")String renwuno, @RequestParam("qzh")String qzh,@RequestParam("qzhcode")String qzhcode,
                             @RequestParam(value="jiandingleader",required=false)Long jiandingleader, @RequestParam(value="chushenpeople",required=false)String chushenpeople, @RequestParam(value="fushenpeople",required=false)String fushenpeople,
                             @RequestParam(value="shendingpeople",required=false)Long shendingpeople, @RequestParam("jiandingstartdate")String jiandingstartdate, @RequestParam("categoryId")Long categoryId,@RequestParam(value="mj",required=false)String mj, MultipartFile file) throws IOException {
        int addjob = bgqxIdentifyService.addjob(jiandingrenwuname, renwuno, qzh,qzhcode, jiandingleader, chushenpeople, fushenpeople, shendingpeople, jiandingstartdate, categoryId, file,remark,mj);
        return toAjax(addjob);
    }
    /** 获取任务信息 */
    @Log(title = "获取保管期限鉴定任务信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getjobinfo/{Id}")
    public AjaxResult getjobinfo(@PathVariable("Id") Long Id)
    {
        return success(bgqxIdentifyService.getjobinfo(Id));
    }
    /** 上传文件 */
    @Log(title = "上传保管期限鉴定任务附件", businessType = BusinessType.UPLOAD)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("renwuid")Long renwuid,@RequestParam(value="mj",required=false)String mj,MultipartFile file) throws IOException {
        TenantYqJdFile upload = bgqxIdentifyService.upload(renwuid,mj, file);
        return success(upload);
    }
    /** 修改任务信息 */
    @Log(title = "更新保管期限鉴定任务信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatejobinfo")
    public AjaxResult updatejobinfo(@RequestBody TenantYqbgqxjdJob yqbgqxjdJob)
    {
        return toAjax(bgqxIdentifyService.updatejobinfo(yqbgqxjdJob));
    }

    /** 删除任务 */
    @Log(title = "删除保管期限鉴定任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/deletejob/{Id}")
    public AjaxResult deletejob(@PathVariable("Id") Long Id)
    {
        return success(bgqxIdentifyService.deletejob(Id));
    }
    /** 撤销任务 */
    @Log(title = "撤销保管期限鉴定任务", businessType = BusinessType.UPDATE)
    @PostMapping("/chexiaojob/{Id}")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:cxjd')")
    public AjaxResult chexiaojob(@PathVariable("Id") Long Id)
    {
        return success(bgqxIdentifyService.chexiaojob(Id));
    }
    /** 添加档案到任务单 */
    @Log(title = "添加档案到保管期限鉴定任务", businessType = BusinessType.INSERT)
    @PostMapping("/addarchive")
    public AjaxResult addarchive(@RequestBody JSONObject json)
    {
        return toAjax(disposeNewService.addArchive(json));
    }
    @Log(title = "保管期限鉴定调档完成", businessType = BusinessType.UPDATE)
    @GetMapping("/completedd/{id}")
    public AjaxResult completedd(@PathVariable("id") Long Id)
    {
        return toAjax(bgqxIdentifyService.completedd(Id));
    }
    /** 删除任务中的档案 */
    @Log(title = "删除保管期限鉴定任务中的档案", businessType = BusinessType.DELETE)
    @PostMapping("/deletearchive")
    public AjaxResult deletearchive(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.deletearchive(json));
    }

    /** 获取任务单内的列表 */
    @Log(title = "获取保管期限鉴定任务中的档案", businessType = BusinessType.SELECT)
    @PostMapping("/getdatalistbyrenwuid")
    public TableDataInfo getdatalistbyrenwuid(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = bgqxIdentifyService.getdatalistbyrenwuid(json);
        return getDataTable(list);
    }
    /** 获取任务总数、初审分配完成数、复审分配完成数 */
    @Log(title = "获取任务总数、初审分配完成数、复审分配完成数", businessType = BusinessType.SELECT)
    @GetMapping("/getcsfsallnumbyrenwuid/{id}")
    public AjaxResult getcsfsallnumbyrenwuid(@PathVariable("id") Long Id)
    {
        return success(bgqxIdentifyService.getcsfsallnumbyrenwuid(Id));
    }

    /** 当前人是否有分配任务的权限 */
    @Log(title = "当前人是否有分配任务的权限", businessType = BusinessType.SELECT)
    @GetMapping("/hasfenpeipro/{id}")
    public AjaxResult hasfenpeipro(@PathVariable("id") Long id)
    {
        return success(bgqxIdentifyService.hasfenpeipro(id));
    }

    /** 当前人是否有修改任务的权限 */
    @Log(title = "当前人是否有修改任务的权限", businessType = BusinessType.SELECT)
    @GetMapping("/hasupdatepro/{id}")
    public AjaxResult hasupdatepro(@PathVariable("id") Long id)
    {
        return success(bgqxIdentifyService.hasupdatepro(id));
    }

    /** 平均初审分配获取任务名/总数/初审人员 */
    @Log(title = "平均初审分配获取任务名/总数/初审人员", businessType = BusinessType.SELECT)
    @GetMapping("/getinfonumperson/{id}")
    public AjaxResult getinfonumperson(@PathVariable("id") Long id)
    {
        return success(bgqxIdentifyService.getinfonumperson(id));
    }

    /** 初审/复审平均分配列表 */
    @Log(title = "初审/复审平均分配列表", businessType = BusinessType.SELECT)
    @PostMapping("/cspjfplist")
    public TableDataInfo cspjfplist(@RequestBody JSONObject json)
    {

        List<Map<String,Object>> list = bgqxIdentifyService.cspjfplist(json);
        return getDataTable(list);
    }

    /** 平均初审分配 */
    @Log(title = "平均初审分配", businessType = BusinessType.UPDATE)
    @PostMapping("/pjfprw")
    public AjaxResult pingjunfenpeirenwu(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.pingjunfenpeirenwu(json));
    }

    /** 标记分配 */
    @Log(title = "标记分配", businessType = BusinessType.UPDATE)
    @PostMapping("/markfp")
    public AjaxResult markfp(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.markfp(json));
    }

    /** 手动分配列表 */
    @Log(title = "手动分配列表", businessType = BusinessType.UPDATE)
    @PostMapping("/sdfplist")
    public TableDataInfo sdfplist(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = bgqxIdentifyService.sdfplist(json);
        return getDataTable(list);
    }

    /** 提交手动分配 */
    @Log(title = "提交手动分配", businessType = BusinessType.UPDATE)
    @PostMapping("/commitsdfp")
    public AjaxResult commitsdfp(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.commitsdfp(json));
    }

    /** 重新分配 */
    @Log(title = "重新分配", businessType = BusinessType.UPDATE)
    @PostMapping("/refp")
    public AjaxResult refp(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.refp(json));
    }

    /** 调整人员 */
    @Log(title = "调整人员", businessType = BusinessType.UPDATE)
    @PostMapping("/tzry")
    public AjaxResult tzry(@RequestBody JSONObject json)
    {
        return toAjax(bgqxIdentifyService.tzry(json));
    }

    /** 发起鉴定 */
    @Log(title = "发起鉴定", businessType = BusinessType.UPDATE)
    @PostMapping("/fqjd/{renwuid}")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:fqjd')")
    public AjaxResult fqjd(@PathVariable("renwuid") Long renwuid)
    {
        return toAjax(bgqxIdentifyService.fqjd(renwuid));
    }

    /** 追踪任务状态 */
    @Log(title = "追踪任务状态", businessType = BusinessType.SELECT)
    @GetMapping("/followd/{renwuid}")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:follow')")
    public AjaxResult followd(@PathVariable("renwuid") Long renwuid)
    {
        return success(bgqxIdentifyService.followd(renwuid));
    }

    /** 获取当前人的初审任务 */
    @Log(title = "获取当前人的初审任务", businessType = BusinessType.SELECT)
    @GetMapping("/getchushenjob")
    public AjaxResult getchushenjob()
    {
        return success(bgqxIdentifyService.getchushenjob());
    }

    /** 获取当前人的初审数量 */
    @Log(title = "获取当前人的初审数量", businessType = BusinessType.SELECT)
    @GetMapping("/getchushennum/{renwuid}/{userId}")
    public AjaxResult getchushennum(@PathVariable("renwuid") Long renwuid,@PathVariable("userId") Long userId)
    {
        return success(bgqxIdentifyService.getchushennum(renwuid,userId));
    }

    /** 获取当前人初审列表 */
    @Log(title = "获取当前人初审列表", businessType = BusinessType.SELECT)
    @PostMapping("/cssplist")
    public TableDataInfo cssplist(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = bgqxIdentifyService.cssplist(json);
        return getDataTable(list);
    }

    /** 初审/复审提交 */
    @Log(title = "初审/复审提交", businessType = BusinessType.UPDATE)
    @PostMapping("/chushentijiao")
    public AjaxResult chushentijiao(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.chushentijiao(json));
    }

    /** 修改审定开放控制 */
    @Log(title = "修改审定保管期限", businessType = BusinessType.UPDATE)
    @PostMapping("/updateshending")
    public AjaxResult updateshending(@RequestBody JSONObject json)
    {
        return success(disposeNewService.updateshending(json));
    }

    /** 修改鉴定备注 */
    @Log(title = "修改鉴定备注", businessType = BusinessType.UPDATE)
    @PostMapping("/updatebeizhu")
    public AjaxResult updatebeizhu(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.updatebeizhu(json));
    }

    /** 获取内部列表 */
    @Log(title = "获取内部列表", businessType = BusinessType.SELECT)
    @PostMapping("/getdetaillist")
    public TableDataInfo getdetaillist(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = bgqxIdentifyService.getdetaillist(json);
        return getDataTable(list);
    }

    /** 获取当前人的复审任务 */
    @Log(title = "获取当前人的复审任务", businessType = BusinessType.SELECT)
    @GetMapping("/getfushenjob")
    public AjaxResult getfushenjob()
    {
        return success(bgqxIdentifyService.getfushenjob());
    }

    /** 获取当前人的复审数量 */
    @Log(title = "获取当前人的复审数量", businessType = BusinessType.SELECT)
    @GetMapping("/getfushennum/{renwuid}/{userid}")
    public AjaxResult getfushennum(@PathVariable("renwuid") Long renwuid,@PathVariable("userid") Long userid)
    {
        return success(bgqxIdentifyService.getfushennum(renwuid,userid));
    }

    /** 获取当前人复审列表 */
    @Log(title = "获取当前人复审列表", businessType = BusinessType.SELECT)
    @PostMapping("/fssplist")
    public TableDataInfo fssplist(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = bgqxIdentifyService.fssplist(json);
        return getDataTable(list);
    }

    /** 抽查 */
    @Log(title = "抽查", businessType = BusinessType.UPDATE)
    @PostMapping("/choucha")
    public AjaxResult choucha(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.choucha(json));
    }

    /** 获取当前人的审定任务 */
    @Log(title = "获取当前人的审定任务", businessType = BusinessType.SELECT)
    @GetMapping("/getsdjoblist")
    public AjaxResult getsdjoblist()
    {
        return success(bgqxIdentifyService.getsdjoblist());
    }

    /** 获取当前人审定列表 */
    @Log(title = "获取当前人审定列表", businessType = BusinessType.SELECT)
    @PostMapping("/sdlist")
    public TableDataInfo sdlist(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = disposeNewService.sdlist(json);
        return getDataTable(list);
    }

    /** 审定提交 */
    @Log(title = "审定提交", businessType = BusinessType.UPDATE)
    @PostMapping("/shendingtijiao")
    public AjaxResult shendingtijiao(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.shendingtijiao(json));
    }

    /** 修改审定结果 */
    @Log(title = "修改审定结果", businessType = BusinessType.UPDATE)
    @PostMapping("/changesdresult")
    public AjaxResult changesdresult(@RequestBody JSONObject json)
    {
        return success(disposeNewService.changesdresult(json));
    }

    /** 鉴定生效 */
    @Log(title = "鉴定生效", businessType = BusinessType.UPDATE)
    @PostMapping("/jiandingshengxiao")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:jdsx')")
    public AjaxResult jiandingshengxiao(@RequestBody JSONObject json)
    {
        return success(disposeNewService.jiandingshengxiao(json));
    }

    /** 再次鉴定 */
    @Log(title = "再次鉴定", businessType = BusinessType.UPDATE)
    @PostMapping("/jiandingagin")
    public AjaxResult jiandingagin(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.jiandingagin(json));
    }

    /** 统计 */
    @Log(title = "统计", businessType = BusinessType.SELECT)
    @PostMapping("/tongji")
    public AjaxResult tongji(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.tongji(json));
    }

    /** 获取初审/复审人员 */
    @Log(title = "获取初审/复审人员", businessType = BusinessType.SELECT)
    @PostMapping("/getuser")
    public AjaxResult getuser(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.getuser(json));
    }

    /** 导出任务表 */
    @Log(title = "导出任务表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportjob")
    @PreAuthorize("@ss.hasPermi('archive:bgqx:export')")
    public void exportjob(@RequestParam("ids") String idsstring, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("保管期限鉴定任务导出表"+ DateUtils.dateTimeNow("yyyyMMddHHmmss"), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<List<String>> headList = bgqxIdentifyService.getexportjobth(); //表头
        List list= Arrays.asList(idsstring.split(","));
        List<List<String>> dataList = bgqxIdentifyService.getexportjobdata(list); //数据
        EasyExcel.write(response.getOutputStream()).head(headList).sheet("保管期限鉴定任务导出表").doWrite(dataList);
    }

    @Log(title = "导出记录中的档案条目", businessType = BusinessType.EXPORT)
    @PostMapping("/exportjobda")
    public void exportjobda(@RequestParam(value = "renwuid")Long renwuid,@RequestParam(value = "menuId")Long menuId,@RequestParam(value = "ids")String ids,@RequestParam(value = "order",required = false)String order,@RequestParam(value = "fields")String fields, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        JSONObject json=new JSONObject();
        json.put("renwuid",renwuid);
        json.put("menuId",menuId);
        List list= Arrays.asList(ids.split(","));
        json.put("ids",list);
        json.put("order",order);
        json.put("fields",fields);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("保管期限任务内数据导出表"+ DateUtils.dateTimeNow("yyyyMMddHHmmss"), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<List<String>> headList = bgqxIdentifyService.exportjobdath(json); //表头
        List<List<String>> dataList = bgqxIdentifyService.exportjobdadata(json); //数据
        EasyExcel.write(response.getOutputStream()).head(headList).sheet("保管期限任务内数据导出表").doWrite(dataList);
    }

    /** 统计导出 */
    @Log(title = "统计导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exporttongji")
    public void exporttongji(@RequestParam(value = "type")String type,@RequestParam(value = "level",required = false)String level,@RequestParam(value = "userid",required = false)Long userid,HttpServletResponse response) throws IOException {
        JSONObject json=new JSONObject();
        json.put("type",type);
        json.put("level",level);
        json.put("userid",userid);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("保管期限鉴定统计导出表"+ DateUtils.dateTimeNow("yyyyMMddHHmmss"), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<List<String>> headList = bgqxIdentifyService.exporttongjith(json); //表头
        List<List<String>> dataList = bgqxIdentifyService.exporttongjidata(json); //数据


        EasyExcel.write(response.getOutputStream()).head(headList).sheet("保管期限鉴定统计导出表").doWrite(dataList);
    }
    /** 获取初审/复审人员 */
    @Log(title = "根据任务id获取初审/复审人员", businessType = BusinessType.SELECT)
    @PostMapping("/getuserbyrenwuid")
    public AjaxResult getuserbyrenwuid(@RequestBody JSONObject json)
    {
        return success(bgqxIdentifyService.getuserbyrenwuid(json));
    }

    //判断能否修改门类
    @PostMapping("/editcate/{id}")
    public AjaxResult editcate(@PathVariable("id") Long id)
    {
        return success(bgqxIdentifyService.editcate(id));
    }

    @Log(title = "下载保管期限清册", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadBgqxList/{renwuid}")
    public ResponseEntity<Resource> downloadDestroyList(@PathVariable("renwuid") Long renwuid)
    {
        String path = bgqxIdentifyService.download(renwuid);
        // 加载文件作为资源
        File file = new File(path);

        // 确保文件存在
        if (!file.exists() || !file.canRead()) {
            throw new ServiceException("文件不存在或不可读!");
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (IOException e) {
            // 记录异常信息
            logger.error(e.getMessage(),e);
            throw new ServiceException("读取文件时发生错误"+e.getMessage());
        }
    }
}
